#include "TerminalControl.h"

CTerminalControl::CTerminalControl()
{
}

CTerminalControl::~CTerminalControl()
{

}

//函数名：
//函数功能:
//函数参数：
//返回值
bool CTerminalControl::Init()
{
    SerialPort = CSerialPort::GetInstance();
    if(!SerialPort)
        return false;

    Queue = CQueue::GetInstance();
    if(!Queue)
        return false;

    DevCreater = new CDevCreater();
    if(!DevCreater)
        return false;

    return true;
}

//函数名：
//函数功能:
//函数参数：
//返回值:
void CTerminalControl::Cleanup()
{
    SerialPort->Cleanup();

    Queue->Cleanup();

    InfoContainer->Cleanup();

    if(DevCreater)
    {
        delete DevCreater;
        DevCreater = 0;
    }
}

//函数名：
//函数功能:
//函数参数：
//返回值:
void CTerminalControl::SendCmd()
{
    int result;
    while(Queue->Size())
    {
        int DevType;
        string Cmd, ReturnData;
        CTerminalDev * TerminalDev = NULL;
        Queue->Pop(Cmd);
        if(SerialPort->Run(Cmd, ReturnData) == false)
            cout << "Cannot receive the terminaldev's message, please check the terminaldev." <<endl;
        else
        {
            string CURID(ReturnData.begin(), ReturnData.begin() + 4);
            InfoContainer->GetTerminalTypeInfo(CURID, DevType);
            TerminalDev = DevCreater->CreateTerminalDev(DevType);
            result = TerminalDev->ReturnOK(ReturnData);
            if(!result)
                cout << "CURID: " << CURID << "'s devic teminal return wrong message" << endl;

            if(TerminalDev)
            {
                delete TerminalDev;
                TerminalDev = NULL;
            }
        }
    }
}

//函数名：
//函数功能:
//函数参数：
//返回值:
bool CTerminalControl::Run(int &CollectFlag, int &TerminalFlag, pthread_mutex_t & ComLock)
{
    pthread_mutex_lock(& ComLock);
    if(CollectFlag == COLLECTFREE && Queue->Size() > 0)
    {
        cout << "TerminalControl Run..." << endl;
        TerminalFlag = TERMINALBUSY;
        //pthread_mutex_unlock(& ComLock);
        SendCmd();
        TerminalFlag = TERMINALFREE;
        pthread_mutex_unlock(& ComLock);
    }
//    else
//    {
//        pthread_mutex_unlock(& ComLock);
//        while(CollectFlag == COLLECTBUSY)
//        {
//            usleep(1000);
//        }
//    }
    return true;
}
